package com.msun.auth.utils.interceptor;

import lombok.ToString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 类描述：
 *
 * @ClassName AuthInterceptor
 * @Description TODO
 * @Author gj
 * @Date 2023/8/23 21:13
 * @Version 1.0
 */

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Qualifier("ajax")
    @Autowired
    private RestTemplate ajax;

    @Value("${auth.host}")
    private String authHost;

    @ToString
    public static class BizResponse {
        private String code;
        private String message;
        private AuthContext.Context data;

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public AuthContext.Context getData() {
            return data;
        }

        public void setData(AuthContext.Context data) {
            this.data = data;
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null || "".equals(token)) {
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "无效身份");
            return false;
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("token", token);
        ResponseEntity<BizResponse> res = null;
        try {
            res = ajax.exchange(
                    authHost + "/auth/open/apiAuth",
                    HttpMethod.GET,
                    new HttpEntity<String>(headers),
                    BizResponse.class);
        } catch (Exception e) {
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "无效身份");
            return false;
        }
        if (res == null || res.getStatusCodeValue() != 200 || res.getBody() == null || !"Success".equals(res.getBody().code)) {
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "无效身份");
            return false;
        }
        AuthContext.Context ctx = res.getBody().data;
        String uri = request.getRequestURI().toLowerCase();
        if ((uri.contains("/edit") ||
                uri.contains("/create") ||
                uri.contains("/add") ||
                uri.contains("/insert") ||
                uri.contains("/update") ||
                uri.contains("/change") ||
                uri.contains("/modify") ||
                uri.contains("/reset") ||
                uri.contains("/del") ||
                uri.contains("/delete") ||
                uri.contains("/remove") ||
                uri.contains("/clear")) && ctx.getRoleLevel() < 10) {
            response.sendError(HttpStatus.FORBIDDEN.value(), "您没有权限做修改操作");
            return false;
        }
        AuthContext.set(ctx);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContext.remove();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}